package com.simple.mq.sdk.consumer;

import com.alibaba.fastjson.JSON;
import com.simple.mq.common.util.DateUtil;
import com.simple.mq.common.entity.po.SimpleMessage;
import com.simple.mq.sdk.client.SimpleMQClient;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;

/**
 * 项目: simple-mq
 *
 * 功能描述:
 *
 * @author: WuChengXing
 *
 * @create: 2023-09-04 14:39
 **/
public class SimpleMqConsumer {

    private final List<String> registerInfo = new ArrayList<>();
    private final SimpleMQClient client;

    public SimpleMqConsumer(URI serverUri, String name) {
        this.client = new SimpleMQClient(serverUri, name, 0);
        try {
            client.connectBlocking();
        } catch (InterruptedException e) {
            //
        }
    }

    /**
     * 为该Client注册绑定一系列新的queue
     *
     * @param queueNames queue的名称
     * @param append     true表示追加绑定，false表示覆盖绑定
     */
    public void register(List<String> queueNames, boolean append) {
        if (!append) {
            registerInfo.clear();
        }
        registerInfo.addAll(queueNames);

        SimpleMessage packaged = new SimpleMessage(0, null, JSON.toJSONString(queueNames), DateUtil.getLocalTime());
        client.send(JSON.toJSONString(packaged));

    }

    /**
     * 为该Client注册绑定一个新的queue
     *
     * @param queueName queue的名称
     * @param append    true表示追加绑定，false表示覆盖绑定
     */
    public void register(String queueName, boolean append) {
        register(Collections.singletonList(queueName), append);
    }


    /**
     * 函数式编程，自定义消息处理方式，由被调用方提供方法参数
     *
     * @param action 自定义接口函数
     */
    public void onMessage(Consumer<String> action) {
        client.setOnMessageAction(action);
    }

    /**
     * 获取注册绑定信息
     *
     * @return registerInfo
     */
    public List<String> getRegisterInfo() {
        return Collections.unmodifiableList(registerInfo);
    }
}
